/**
 * 
 */
package com.tomica.mailsigner.signoffice;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.Wsdl2Code.WebServices.SignService.SignService;
import com.Wsdl2Code.WebServices.SignService.VectorByte;
import com.entersafe.safeca.Constant;
import com.tomica.mailsigner.common.MailSignerEvents;
import com.tomica.mailsigner.token.Token;

/**
 * @author TOMICALAB
 *
 */
public class SignOfficeModel {
	public static final String TAG = "SignOffice";
	
	public Context context; 
	private Token token;
	private SignService service;
	private Handler handler;
	
	
	public SignOfficeModel(Context ctx, Handler hdl){
		context = ctx;
		handler = hdl;
		token = new Token(ctx, null);
		MailSignerEvents mailHandleEvents = new MailSignerEvents(handler);
		service = new SignService(mailHandleEvents);
	}
	
	public void signOffice(byte[] pdfBase64, String pin){
		// TODO : signing here :)
		Log.v(TAG, "Starting ^^");
		
		uploadOfficeFile(pdfBase64, pin);
		
		return;
	}
	
	public void signObjectString(String data, String pin){
		Log.v(TAG, "Sign object ^^");
		byte[] byteData = data.getBytes();
		String signedData = token.signDataBase64(byteData, pin);
		
		// TODO : handle when sign error
		Message msg = new Message();
        msg.what = Constant.OFFICE_SIGNED_PKCS_OK;
        msg.obj  = signedData;
        handler.sendMessage(msg);
	}

	public void getSignedOfficeFile(String randomString, String signatureBase64){
		Log.v(TAG, "Get Signed Office file");
		try {
			service.GetSignedOfficeFileAsync(randomString, signatureBase64);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void uploadOfficeFile(byte[] fileData, String pin){
		Log.v(TAG, "Upload Office file");
		Log.v(TAG, "Office ByteArray size: "+fileData.length);
		String certBase64 = token.getCertBase64(pin);
		
		try {
			VectorByte vector  = new VectorByte(fileData);
			service.UploadOfficeFileAsync(vector, certBase64);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] getBytes(InputStream inputStream) throws IOException {
		
		ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
		int bufferSize = 1024;
		byte[] buffer = new byte[bufferSize];

		int len = 0;
		while ((len = inputStream.read(buffer)) != -1) {
			byteBuffer.write(buffer, 0, len);
		}
		return byteBuffer.toByteArray();
	}

}
